package com.hd.trans.share;

import android.util.Log;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import java.util.HashMap;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

public class PostInterceptor implements Interceptor {
    private static final String TAG = "PostInterceptor";
    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Gson gson = new GsonBuilder().registerTypeAdapter(new TypeToken<HashMap<String, Object>>(){}.getType(),new MapTypeAdapter()).create();
        Request request = chain.request();
        HttpUrl httpUrl = request.url();
        String encodedPath = httpUrl.encodedPath();
//        LOG.i(TAG, "httpUrl：$httpUrl")
        RequestBody body = request.body();
        if (body != null) {
            Buffer buffer = new Buffer();
            body.writeTo(buffer);
            Charset charset = Charset.forName("UTF-8");
            MediaType contentType = body.contentType();
            if (contentType != null) {
                charset = contentType.charset(charset);
            }
            String content = buffer.readString(charset);
            try {
                Type type = new TypeToken<HashMap<String, Object>>(){}.getType();
                HashMap<String, Object>  params= gson.fromJson(content, type);
                if (encodedPath.contains("/api/v4") && params.size() > 0 && params.containsKey("productinfo")) {
                    params.put("productinfo", PublicBeanManager.mProductInfo_v4);
                    if (params.containsKey("timestamp")) {
                        params.put("timestamp", PublicBeanManager.getInstance().getServiceTime());
                    }
                    if (params.containsKey("datasign")) {
                        params.remove("datasign");
                    }
                    String md5Json = ReqUtil.appendArgumentMapToMd5String(params);
                    params.put("datasign", Md5Util.getMD5(md5Json));
                    String json = gson.toJson(params);
//                    LOG.i(TAG, "new_json：$json")
                    request = request.newBuilder().post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json)).build();
                }
            } catch (Exception e) {
                Log.i(TAG, "拦截设置异常：" + e.getMessage());
                return chain.proceed(chain.request());
            }

        }

        return chain.proceed(request);
    }
}
